<template>
  <s-layout>
    <!-- 顶部轮播图 -->
    <!-- 修改顶部轮播图区域 -->
    <fui-swiper-dot :items="detailData.images" :current="current">
      <swiper class="banner-wrap" circular autoplay @change="onChange">
        <swiper-item v-for="(img, index) in detailData.images" :key="index">
          <image class="banner-image" :src="img" mode="aspectFill" />
        </swiper-item>
      </swiper>
    </fui-swiper-dot>

    <!-- 主要内容区域 -->
    <view class="content-container">
      <!-- 标题和状态 -->
      <view class="header-box">
        <view style="border-left: 8rpx solid #2979ff; padding-left: 20rpx"
          ><text class="title">{{ detailData.title }}</text>
          <view
            style="
              display: flex;
              align-items: center;
              gap: 20rpx;
              margin-top: 20rpx;
            "
          >
            <fui-tag
              :text="detailData.duration + ' '"
              style="
                transform: scale(0.9);
                background: #ecf5ff;
                color: #0052d9;
                border: none;
              "
            ></fui-tag>
            <!-- <text style="color: #4f4e4e; font-size: 26rpx">
              <text
                class="cicon-eye"
                style="color: #a0cfff; margin-right: 10rpx"
              ></text>
              已浏览 {{ detailData.views }} 次
            </text> -->
          </view></view
        >

        <!-- <view class="status-tag" :style="{ background: statusColor }">
        <text :class="statusIcon" size="36rpx" />
        {{ detailData.status }}
      </view> -->
      </view>

      <!-- 基本信息网格 -->
      <view class="info-grid">
        <view class="info-item">
          <text class="cicon-time" style="color: #0052d9; font-size: 48rpx" />
          <view class="info-content">
            <text class="label">演练时间</text>
            <text class="value"
              >{{ detailData.date }} {{ detailData.time }}</text
            >
          </view>
        </view>

        <view class="info-item">
          <text
            class="cicon-location-on"
            style="color: #0052d9; font-size: 58rpx"
          />
          <view class="info-content">
            <text class="label">演练地点</text>
            <text class="value">{{ detailData.address }}</text>
          </view>
        </view>
      </view>

      <!-- 详细信息卡片 -->
      <view class="detail-card">
        <view class="card-header">
          <text class="cicon-info" size="36rpx" color="#4f4e4e" />
          <text class="card-title">演练详情</text>
        </view>

        <view class="card-body">
          <view class="meta-row">
            <view class="meta-item">
              <text class="cicon-person" size="36rpx" />
              参与人数：<fui-tag
                :text="detailData.participants"
                background="#CCCCCC"
                color="#fff"
                theme="light"
                :padding="['12rpx', '18rpx']"
              ></fui-tag
              >人
            </view>
            <view class="meta-item">
              <!-- <text class="cicon-tag" size="36rpx" />
              类型：<fui-tag
                :text="detailData.type"
                background="#CCCCCC"
                color="#fff"
                theme="light"
                :padding="['12rpx', '18rpx']"
              ></fui-tag> -->
            </view>
          </view>

          <!-- 视频模块 -->
          <view
            style="
              position: relative;
              height: 400rpx;
              margin-top: 50rpx;
              border-radius: 16rpx;
            "
          >
            <fui-section
              title="培训视频"
              line-width="3px"
              line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
              isLine
              size="34"
              padding="30rpx"
              style="
                margin-bottom: 100rpx;
                --fui-section-title-color: #1a1a1a;
                --fui-section-line-color: #19be6b;
              "
            />
            <su-video
              style="
                position: relative;
                padding: 0;
                top: 40rpx;
                width: 100%;
                height: 100%;
                --fui-section-title-color: #1a1a1a;
                --fui-section-line-color: #19be6b;
              "
              :src="detailData.videos"
              :poster="detailData.videos"
            />
          </view>

          <!-- 检查文件模块 -->
          <view class="check-box" style="margin-top: 30rpx;">
            <view class="check-box-border">
              <fui-section
                title="检查文件"
                line-width="3px"
                line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
                isLine
                marginBottom="25"
                padding="10rpx 0"
                size="34"
                style="
                  padding: 0;
                  --fui-section-title-color: #1a1a1a;
                  --fui-section-line-color: #19be6b;
                "
              ></fui-section>
              <view class="check-content file-list-container">
                <view v-if="detailData.files && detailData.files.length > 0">
                  <view class="file-item" v-for="(fileUrlInArray, index) in detailData.files" :key="index" @click="openFile(fileUrlInArray)">
                    <image :src="getFileIcon(extractFileTypeFromUrl(fileUrlInArray))" class="file-icon"></image>
                    <text class="file-name">{{ extractFileNameFromUrl(fileUrlInArray) }}</text>
                  </view>
                </view>
                <view v-else class="empty-files">
                  <text>暂无检查文件</text>
                </view>
              </view>
            </view>
          </view>

          <view class="section">
            <fui-section
              title="演练内容"
              line-width="3px"
              line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
              isLine
              size="34"
              padding="30rpx"
              style="
                padding: 0;
                --fui-section-title-color: #1a1a1a;
                --fui-section-line-color: #19be6b;
              "
            ></fui-section>
            <p class="section-content">{{ detailData.content }}</p>
          </view>

          <!-- <view class="section">
            <fui-section
              title="演练流程"
              line-width="3px"
              line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
              isLine
              marginBottom="25"
              padding="30rpx"
              size="34"
              style="
                padding: 0;
                --fui-section-title-color: #1a1a1a;
                --fui-section-line-color: #19be6b;
              "
            ></fui-section>
            <fui-steps
              color="#4f4e4e;"
              activeColor="#0052d9"
              class="steps"
              :items="detailData.steps"
              :current="stepsCurrent"
              direction="column"
              :padding="['0', '32rpx']"
            ></fui-steps>
          </view> -->

          <view class="section">
            <fui-section
              line-width="3px"
              line-color="linear-gradient(to bottom , #0052d9 70%, #ff9900 90%)"
              isLine
              size="34"
              padding="30rpx"
              style="
                padding: 0;
                --fui-section-title-color: #1a1a1a;
                --fui-section-line-color: #19be6b;
              "
              title="演练总结"
            ></fui-section>

            <p class="section-content">{{ detailData.purpose }}</p>
          </view>
        </view>
      </view>

      <!-- 参与部门 -->
      <!-- <view class="department-box">
      <text class="cicon-group" size="36rpx" />
      <text>参与部门：{{ detailData.depts.join("、") }}</text>
    </view> -->
    </view>
  </s-layout>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { ref, computed } from "vue";
import sheep from "@/sheep";
import { truncateString } from "@/sheep/helper/utils";

const current = ref(0);
const stepsCurrent = ref(1);

const detailData = ref({});

const truncate = () => {
  const str = detailData.value.address;
  detailData.value.address = truncateString(str, 6);
};

// truncate()
function convertStepsToFormat(steps) {
  return steps.map((step, index) => ({
    title: step,
    text: (index + 1).toString(),
  }));
}
const statusConfig = {
  准备中: { icon: "cicon-LightMode", color: "#0052d9" },
  进行中: { icon: "cicon-whatshot", color: "#FF9900" },
  已结束: { icon: "cicon-stop", color: "#4f4e4e" },
};

const emergencyDetailData = (dr_id) => {
  const params = {
    company_id: sheep.$store("user").userInfo.company_id,
    dr_id: dr_id,
  };
  sheep.$api.qy_emergency.detail(params).then((res) => {
    console.log("res", res);
    console.log("res温度哈市无计划的", res);
    detailData.value = res.data;
    console.log("detailData", detailData.value);
  });
};

// const statusColor = computed(() => statusConfig[detailData.value.status].color);
const statusIcon = computed(() => statusConfig[detailData.value.status].icon);

function onChange(e) {
  current.value = e.detail.current;
}

const pdfIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_acrobat.png";
const wordIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_word.png";
const genericFileIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white.png";
const excelIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_excel.png";
const pptIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_powerpoint.png";

const extractFileNameFromUrl = (fileUrl) => {
  if (!fileUrl || typeof fileUrl !== 'string') return '未知文件';
  try {
    const url = new URL(fileUrl);
    const pathname = url.pathname;
    const parts = pathname.split('/');
    return parts[parts.length - 1] || '未知文件';
  } catch (e) {
    const parts = fileUrl.split('/');
    return parts[parts.length - 1] || '未知文件';
  }
};

const extractFileTypeFromUrl = (fileUrl) => {
  if (!fileUrl || typeof fileUrl !== 'string') return '';
  const extension = fileUrl.split('.').pop();
  return extension ? extension.toLowerCase() : '';
};

const getFileIcon = (fileType) => {
  const type = fileType ? fileType.toLowerCase() : '';
  if (type.includes('pdf')) return pdfIconUrl;
  if (type.includes('doc') || type.includes('docx')) return wordIconUrl;
  if (type.includes('xls') || type.includes('xlsx')) return excelIconUrl;
  if (type.includes('ppt') || type.includes('pptx')) return pptIconUrl;
  return genericFileIconUrl;
};

const openFile = (fileUrl) => {
  if (fileUrl) {
    // #ifdef H5
    window.open(fileUrl, '_blank');
    // #endif
    // #ifndef H5
    uni.downloadFile({
      url: fileUrl,
      success: function (res) {
        var filePath = res.tempFilePath;
        // #ifdef MP-WEIXIN
        uni.openDocument({
          filePath: filePath,
          showMenu: true,
          success: function (res) {
            console.log('打开文档成功（微信小程序）');
          },
          fail: function (err) {
            console.error('打开文档失败（微信小程序）：', err);
            uni.showToast({
              title: '打开文件失败: ' + (err.errMsg || ''),
              icon: 'none'
            });
          }
        });
        // #else
        uni.saveFile({
          tempFilePath: filePath,
          success: function (saveRes) {
            uni.showToast({
              title: '已保存到：' + saveRes.savedFilePath,
              icon: 'none',
              duration: 3000
            });
            console.log('文件已保存到：', saveRes.savedFilePath);
          },
          fail: function (saveErr) {
            console.error('保存文件失败：', saveErr);
            uni.showToast({
              title: '保存文件失败: ' + (saveErr.errMsg || ''),
              icon: 'none'
            });
            uni.showToast({
              title: '下载完成，临时路径：' + filePath,
              icon: 'none',
              duration: 3000
            });
          }
        });
        // #endif
      },
      fail: function(err){
        uni.showToast({
          title: '下载失败: ' + (err.errMsg || ''),
          icon: 'none'
        });
      }
    });
    // #endif
  } else {
    uni.showToast({
      title: '文件链接无效',
      icon: 'none'
    });
  }
};

onLoad((options) => {
  console.log("options", options.id);
  emergencyDetailData(options.id);
  // 假设 detailData.value.file 和 detailData.value.videos 会由 emergencyDetailData 填充
  // 如果需要模拟数据进行测试，可以在此处添加，例如：
  // detailData.value.file = ['https://example.com/sample.pdf'];
  // detailData.value.videos = ['https://example.com/sample.mp4'];
});

uni.hideTabBar();
</script>

<style lang="scss" scoped>
@import "@/sheep/scss/icon/_coloricon.scss";

.check-box {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.1);
}

.check-box-border {
  /* Styles for the border if needed, or remove if check-box handles padding */
}

.file-list-container {
  margin-top: 15rpx;
}
.file-item {
  display: flex;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #eee;
  cursor: pointer;
}
.file-item:last-child {
  border-bottom: none;
}
.file-icon {
  width: 48rpx;
  height: 48rpx;
  margin-right: 20rpx;
}
.file-name {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.empty-files {
  text-align: center;
  color: #999;
  padding: 20rpx 0;
  font-size: 28rpx;
}

.video-list-container {
  width: 100%;
  overflow: hidden;
  margin-top: 20rpx; /* Added margin for spacing */
}
.video-scroll-view {
  white-space: nowrap;
  width: 100%;
  font-size: 0; 
}
.video-item {
  display: inline-block;
  width: 100%; 
  height: 300rpx; /* Or adjust as needed */
  vertical-align: top;
  background-color: #f0f0f0; 
}
/* If videos are displayed one by one full width, no margin-right is needed */
/* .video-item:not(:last-child) {
  margin-right: 20rpx;
} */

.banner-wrap {
  height: 360rpx;

  .banner-image {
    width: 100%;
    height: 100%;
  }
}

.content-container {
}

.header-box {
  padding-inline: 30rpx;
  padding-top: 10rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20rpx 0rpx;

  .title {
    font-size: 40rpx;
    font-weight: 700;
    color: #1a1a1a;
    max-width: 70%;
  }

  .status-tag {
    padding: 12rpx 30rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    color: #fff;
    display: flex;
    align-items: center;
    gap: 10rpx;
  }
}

.info-grid {
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.1);
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  margin-bottom: 30rpx;

  .info-item {
    background: #f8f9fa;
    border-radius: 16rpx;
    padding: 20rpx;
    display: flex;
    align-items: center;
    gap: 20rpx;

    .label {
      font-size: 26rpx;
      color: #4f4e4e;
      display: block;
    }

    .value {
      font-size: 30rpx;
      color: #1a1a1a;
      font-weight: 500;
    }
  }
}

.detail-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.1);

  .card-header {
    display: flex;
    align-items: center;
    gap: 15rpx;
    margin-bottom: 30rpx;

    .card-title {
      font-size: 34rpx;
      font-weight: 600;
      color: #1a1a1a;
    }
  }

  .meta-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 25rpx;

    .meta-item {
      display: flex;
      align-items: center;
      gap: 5rpx;
      font-size: 28rpx;
      color: #4f4e4e;
    }
  }

  .duration-box {
    background: #fcf8e8;
    border-radius: 8rpx;
    padding: 10rpx 0rpx;
    margin-bottom: 25rpx;
    display: flex;
    align-items: center;
    gap: 15rpx;
    color: #cfab8e;
    font-size: 28rpx;
  }

  .section {
    margin-top: 40rpx;
    .steps {
      margin-top: 90rpx;
    }
    &-title {
    }

    &-content {
      font-size: 28rpx;
      line-height: 1.6;
      color: #4f4e4e;
      text-indent: 2em;
      margin-top: 20rpx;
    }

    .step-item {
      padding: 15rpx;
      margin: 10rpx 0;
      background: #f8f9fa;
      border-radius: 8rpx;
      font-size: 28rpx;

      .step-tag {
        display: inline-block;
        padding: 4rpx 12rpx;
        background: linear-gradient(45deg, #0052d9, #4f4e4e);
        color: #fff;
        border-radius: 4rpx;
        margin-right: 15rpx;
      }
    }
  }
}

.department-box {
  margin-top: 30rpx;
  padding: 20rpx;
  background: #f1f1f1;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  gap: 15rpx;
  font-size: 28rpx;
  color: #4f4e4e;
}
</style>
